<?php

namespace App\Http\Controllers\Api\System;

use App\Http\Controllers\Controller;
use App\Libs\Strategy\Context;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class AdminController extends Controller
{
    private $admin;

    public function __construct()
    {
        $this->admin = new Context(new User());
    }

    public function index(Request $request)
    {
        $users = $this->admin->display($request->limit,function($query) use ($request){
            $query->with('roles');
            if($request->keyword)
            {
                $query->where('name','like','%'.$request->keyword.'%')->orWhere('email',$request->keyword);
            }
            return $query;
        });
        return $this->success(['users'=>$users]);
    }

    public function store()
    {
        DB::beginTransaction();
        if($user = $this->admin->setRules($this->validates())->create([],function ($items){
             $items['password'] = Hash::make($items['password']);
             return $items;
        })){
            if(request()->roles)
            {
                $user->assignRole(request()->roles);
            }
            DB::commit();
           return $this->success(['message'=>'添加成功']);
        };
        return $this->error('添加失败');
    }

    public function update(Request $request,$id)
    {
        DB::beginTransaction();
        if($this->admin->setRules($this->validates())->update($id,[],function ($items){
            if($items['password'] == null)
            {
                unset($items['password']);
            }else{
                $items['password'] = Hash::make($items['password']);
            }
            return $items;
        })){
            if(request()->roles)
            {
                $this->admin->find($id)->syncRoles(request()->roles);
            }
            DB::commit();
            return $this->success(['message'=>'更新成功']);
        };
         return $this->error('更新失败');
    }

    private function validates()
    {
        $email = [];

        $password = \request()->route()->getName() == 'admin.update' && empty(\request()->password) ? [] : ['password'=>'min:6|required|confirmed'];
        if(config('app.admin_avater_email') && request()->method() != 'PUT')
        {
             $email = ['email' => 'required|email|unique:users,email,'.\request()->route('admin')];
        }
        $default = [
            'name' => 'required|unique:users,name,'.\request()->route('admin'),
            'avatar' => 'image',
        ];
        return $email+ $default + $password;
    }

    public function destroy($id){
        $user = $this->admin->find($id);
        if($user->is_admin())
        {
            return $this->error('超级管理员不能删除');
        }
        if($user->delete($id))
        {
            return $this->success(['message'=>'删除成功']);
        }else{
              return $this->error('删除失败');
        }
    }
}
